<?php
class Vnf {

    /**
     * Singleton instance
     *
     * Marked only as protected to allow extension of the class. To extend,
     * simply override {@link getInstance()}.
     *
     * @var Vnf
     */
    protected static $_instance = null;

    protected $controllerDirectory = './vietnamfriendly/src/net/vietnamfriendly/user/modules/';
    protected $acceptHost = array('localhost:8080','localhost', '127.0.0.1', 'demo.wo-essen-was.de', 'www.demo.wo-essen-was.de', 'wo-essen-was.de', 'www.wo-essen-was.de');

    /**
     * Singleton instance
     *
     * @return Zend_Controller_Front
     */
    public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }


    /**
     * Constructor
     *
     * Instantiate using {@link getInstance()}; front controller is a singleton
     * object.
     *
     * Instantiates the plugin broker.
     *
     * @return void
     */
    protected function __construct()
    {
        $this->setupAutoLoad();

        // load configuration
        //$config = new Zend_Config_Ini('../config/config.ini');
        $config = new Zend_Config_Ini('../config/config.ini', null
                                ,array('skipExtends'        => true,
                                    'allowModifications' => true));
        
        $layouts = $config->layouts;
        $defaultLayout = isset($layouts) && $layouts->default != ''?$layouts->default :'cms';
        
        $directory = $config->directory;

        $application = $config->application;
        $database = $config->database;
//        $database = $config->database;

        Zend_Registry::set('config', $config);

        $conf = $config->conf;
        define("RECORDS_PER_PAGE", @$conf->recordsPerPage?$conf->recordsPerPage:10);

        define("BASE_PATH", $directory->basePath);
        define("UPLOAD_PATH", $directory->uploadPath);
        define("BASE_DIR", trim($directory->baseDir, '/'));
        define("SRC_PATH", BASE_DIR . $directory->srcPath);
        define("CSS_PATH", BASE_PATH . $directory->srcPath . $directory->css);
        define("JS_PATH", BASE_PATH . $directory->srcPath . $directory->js);
        define("EXT_PATH", JS_PATH . '/ext');
        define("IMAGE_PATH", BASE_PATH . $directory->srcPath . $directory->images);
        define("ICONS_PATH", BASE_PATH . $directory->srcPath . $directory->icons);
        define("DEFAULT_LAYOUT", $defaultLayout);

        $uri = $_SERVER['REQUEST_URI'];

        // GET APPLICATION NAME IN URI
        $applicationPath = substr($uri, strlen(BASE_PATH));

        if ('' == $applicationPath || '/' == $applicationPath){
            // has not any thing in REQUEST_URI
            $applicationName = $application->default;
            $applicationPath = $application->default;
        } else {
            //get application name
            $arrApps = explode('/', $applicationPath);
            // always  has format '/ApplicationName*'
            $applicationName = $arrApps[1];

            //$applicationName = $application->$applicationName == '' ? $application->default:$application->$applicationName;
            $applicationPath = $application->$applicationName == '' ? $application->default:$application->$applicationName;
        }

        define("CURR_APP", $applicationName);
        define("CURR_APP_PATH", $applicationPath);

        $conf = $config->conf;
        $htaccess = @$conf->htaccess;

        if (isset($conf->htaccess)) {
            $htaccess = @$conf->htaccess;
        } else {
            $htaccess = true;
        }
        
        if ($htaccess == true) {
            define("BASE_URL", BASE_PATH . '/' . $applicationName);
        } else {
            define("BASE_URL", BASE_PATH . '/' . $applicationName . '/index.php');
        }

        $db = Zend_Db::factory($database->adapter,$database->config->toArray());
        Zend_Db_Table::setDefaultAdapter($db);
        Zend_Registry::set('db', $db);

    }

    public function setupAutoLoad() {

        include_once('Zend/Loader/Autoloader.php');

        $loader = Zend_Loader_Autoloader::getInstance();
        $loader->setFallbackAutoloader(true);
        $loader->suppressNotFoundWarnings(false);
    }

    /**
     *
     * @param $application = user/admin
     * @return void
     */
    public function buildSite($application = null) {


        $host = $_SERVER['HTTP_HOST'];

        if (!in_array($host, $this->acceptHost))
            die('Please contact administrator');

        if (null == $application || '' == $application) {
            $application = CURR_APP_PATH;
        }

        $modulesPath = SRC_PATH . '/' . $application . '/modules';

        /*
        if ($application == 'user') {
            $router = Zend_Controller_Front::getInstance()->getRouter();
            $router->addRoute(
                'cms', new Zend_Controller_Router_Route('/*',
                     array(
                        'module' => 'index',
                        'controller' => 'index',
                        'action' => 'index'
                    ))
            );
        }
        */

        $sourceDirHandle = opendir($modulesPath);

        $allControlers = array();
        $allModels = array();
        while (FALSE !== ($fileName = readdir($sourceDirHandle)) )
        {
            if ($fileName != "." && $fileName != ".." && strpos($fileName, '.') !== 0)
            {
                if (is_dir($modulesPath . "/" . $fileName) && $fileName != "." && $fileName != "..")
                {
                    $allControlers[$fileName] = "$modulesPath/$fileName/controllers";
                    //                    echo getcwd() . "/$modulesPath/$fileName/models";
                    /*set_include_path(get_include_path()
                    . PATH_SEPARATOR . "./$modulesPath/$fileName/models");*/
                }
            }
        }

        // include folder contain all Models
        set_include_path(get_include_path()
                    . PATH_SEPARATOR . SRC_PATH . "/db");

        $frontController = Zend_Controller_Front::getInstance();
        $frontController->setControllerDirectory($allControlers);
        $frontController->throwExceptions(true);

        $frontController->setDefaultModule('index');

        try {
        $frontController->dispatch();
            // Count and show query
            $db = Zend_Registry::get('db');
            $profiler = $db->getProfiler ();
            //echo "<hr>Total Queries: " . $profiler->getTotalNumQueries ();
            //print_r($profiler->getQueryProfiles());
        } catch(Exception $ex) {
            echo "Error: " . $ex->getMessage();
            
            
        }
    }

    public static function getElements($page_id = 1) {
    
        try {
            $elements = Zend_Registry::get('elements');
            if (count($elements) > 0)
                return $elements;
        } catch(Exception $ex) {}
        // get all element of this page
        $objElement = new Element();
        $allElement = $objElement->getElementOfPage($page_id);

        $elements = array();
        if (count($allElement) > 0) {
            foreach($allElement as $element):
                $elements[$element->element_name] = $element;
            endforeach;
        }        
        Zend_Registry::set('elements', $elements);
        
        return $elements;
    }
    
    public static function getConfigs($key = '') {
        if ($key == null || $key == '')
            return Zend_Registry::get('config');
            
        $config =  Zend_Registry::get('config');
        
        $array = $config->$key;
        if (isset($array))
            return $array;
        
        return array();
    }

    /*    public static function getBlockCms() {
        //        echo "<input type='text' id='cmscookie' name='cmscookie' value='' size='200'>";
        //        try
        $result = array();
        try {
            $result =  Zend_Registry::get('blockcms');
        }catch(Exception $ex){
            Zend_Registry::set('blockcms', array());
        }
        return $result;
        //        Zend_Registry::set('blockcms', array());
    }

    public function startCms() {
        //        echo "<input type='text' id='cmscookie' name='cmscookie' value='' size='200'>";
        try {

            Zend_Registry::set('blockcms', array());
        }catch(Exception $ex){
        }
    }

    public function buildCms() {
        $manageBlockCms = Zend_Registry::get('blockcms');
        //print_r($manageBlockCms);
    }*/
}